importScripts('./node_modules/@babel/standalone/babel.min.js')

const globalMap = {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'antd': 'antd',
    'dayjs': 'dayjs'
}
// 安装完成 -> 激活
self.addEventListener('install', event => {
    event.waitUntil(self.skipWaiting())
});

self.addEventListener('activate', event => {
    event.waitUntil(clients.claim());
});
const headers = new Headers({
    'Content-Type': 'application/javascript'
});
self.addEventListener('fetch', event => {
    const { request: { url } } = event;
    console.log('Req ', url)
    if (Object.keys(globalMap).some(key => url.includes(`node_modules/${key}`))) {
        event.respondWith(
            fetch(url)
            .then(resp => resp.text())
            .then(body => {
                return new Response(`
                    const head = document.getElementsByTagName('head')[0];
                    const script = document.createElement('script');
                    script.setAttribute('type', 'text/javascript');
                    script.appendChild(document.createTextNode(${JSON.stringify(body)}));
                    head.appendChild(script);
                    export default window.${globalMap[/node_modules\/(.*?)\//.exec(url)[1]]};    
                `, { headers })
            })
        )
    }
    if (url.endsWith('.jsx')) {
        // need compiler
        event.respondWith(fetch(url).then(resp => resp.text()).then(body => {
            const code = Babel.transform(body, {
                presets: ['react']
            }).code;
            return new Response(code, { headers })
        }))
    }
})